package cn.jbolt.core.db.datasource;

import cn.jbolt.core.base.JBoltMsg;
import cn.jbolt.core.kit.JBoltUserKit;
import cn.jbolt.core.model.DatasourceFilter;
import cn.jbolt.core.service.base.JBoltBaseService;
import com.jfinal.kit.Ret;
/**
 * 数据源过滤设置Service
 * @ClassName:  DatasourceFilterService
 * @author: JFinal学院-小木 QQ：909854136
 * @date:   2021年9月25日
 */
public class DatasourceFilterService extends JBoltBaseService<DatasourceFilter> {
	private DatasourceFilter dao = new DatasourceFilter().dao();
	@Override
	protected DatasourceFilter dao() {
		return dao;
	}

	/**
	 * 不需要生成的表名（全部小写），直接完整的表名，一般都是一些数据库内置表什么的
	 * 这里默认给了几个，需要的自己加
	 */
	public static final String defaultTableNameFilters="dept,emp,salgrade,bonus,dtproperties";
	/**
	 * 这里是判断表名中有包含以下字符串的需要过滤掉
	 * 一些分表不需要生成 例如jb_wechat_user_
	 * 一些sqlite中的临时表和内置不需要
	 */
	public static final String defaultTableNameContains="sqlite_,_old_,jb_";

	/**
	 * 这里是判断表名符合的正则表达式
	 */
	public static final String defaultTableNamePatterns="jb_wechat_user_-?[1-9]\\d*";

	public Ret save(DatasourceFilter filter) {
		if(filter == null || isOk(filter.getId()) || notOk(filter.getName())|| notOk(filter.getConfigName())) {
			return fail(JBoltMsg.PARAM_ERROR);
		}
		if(existsName(filter.getConfigName())) {
			return fail(JBoltMsg.DATA_SAME_NAME_EXIST+"["+filter.getConfigName()+"]");
		}
		Long userId = JBoltUserKit.getUserId();
		filter.setCreateUserId(isOk(userId)?userId:0);
		filter.setUpdateUserId(isOk(userId)?userId:0);
		if(notOk(filter.getTableNameFilter())) {
			filter.setTableNameFilter(defaultTableNameFilters);
		}
		if(notOk(filter.getTableNameContains())) {
			filter.setTableNameContains(defaultTableNameContains);
		}
		if(notOk(filter.getTableNamePatterns())) {
			filter.setTableNamePatterns(defaultTableNamePatterns);
		}
		boolean success = filter.save();
		return ret(success);
	}

	public Ret update(DatasourceFilter filter) {
		if(filter == null || notOk(filter.getId())) {
			return fail(JBoltMsg.PARAM_ERROR);
		}
		DatasourceFilter dbFilter = findById(filter.getId());
		if(dbFilter == null) {
			return fail(JBoltMsg.DATA_NOT_EXIST);
		}
		if(existsName(filter.getConfigName(),filter.getId())) {
			return fail(JBoltMsg.DATA_SAME_NAME_EXIST+"["+filter.getConfigName()+"]");
		}
		Long userId = JBoltUserKit.getUserId();
		filter.setUpdateUserId(isOk(userId)?userId:0);
		if(notOk(filter.getTableNameFilter())) {
			filter.setTableNameFilter(defaultTableNameFilters);
		}
		if(notOk(filter.getTableNameContains())) {
			filter.setTableNameContains(defaultTableNameContains);
		}
		if(notOk(filter.getTableNamePatterns())) {
			filter.setTableNamePatterns(defaultTableNamePatterns);
		}
		boolean success = filter.update();
		return ret(success);
	}

	@Override
	protected int systemLogTargetType() {
		// TODO Auto-generated method stub
		return 0;
	}

}
